#include <memory>
#include <iostream>
#include <fstream>

using std::cout;
using std::endl;
using std::unique_ptr;
using std::shared_ptr;
using std::ofstream;

class Point
{
public:
    Point(int ix, int iy)
    : _ix(ix)
    , _iy(iy)
    {   cout << "Point(int,int)" << endl;   }

    ~Point()
    {   cout << "~Point()" << endl; }

    void print() const
    {   
        cout << "(" << _ix
             << "," << _iy
             << ")" << endl;
    }

private:
    int _ix;
    int _iy;
};

struct OfstreamCloser
{
    void operator()(ofstream * pofs)
    {
        if(pofs) {
            pofs->close();
            cout << ">> ofstream.close()" << endl;
        }
    }
};

void test1()
{
    ofstream ofs("1.txt", std::ios::app);
    if(!ofs.good()) {
        cout << "ofstream open file error" << endl;
        return ;
    }
    //指定第二个模板参数为OfstreamCloser
    unique_ptr<ofstream, OfstreamCloser> up(&ofs);

    ofs << "this is a deletor test\n";


    //希望以下语句能自动执行，防止忘了调用文件输出流的close函数
    //ofs. close();//关闭文件输出流流
}

void test2()
{
    ofstream ofs("1.txt", std::ios::app);
    if(!ofs.good()) {
        cout << "ofstream open file error" << endl;
        return ;
    }
    /* OfstreamCloser oc; */
    /* shared_ptr<ofstream> sp(&ofs, oc); */
    //构造函数的第二个参数传递是一个临时对象
    shared_ptr<ofstream> sp(&ofs, OfstreamCloser());

    ofs << "this is another deletor test\n";
}

int main()
{
    /* test1(); */
    test2();

    return 0;
}

